package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.GetRelationResponse;
import com.woyao.core.model.Relation;
import com.woyao.core.model.Talk;
import com.woyao.core.service.AccountService;
import com.woyao.core.service.ChanceService;
import com.woyao.core.util.CollectionUtil;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.IOException;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;


public class RelationActivity extends AppCompatActivity {

    Boolean is_new = false;

    Button commentBtn;
    Button toggleBtn;
//    Button addPartnerBtn;
//    Button confirmBtn;
//    Button addBtn;
    LinearLayout consultAction;


//    android.support.v7.widget.CardView agreementArea;
    android.support.v7.widget.CardView commentArea;
    LinearLayout actionArea;
    private LinearLayout partnersInfo;


//    List<DemandSummary> demands = new ArrayList<DemandSummary>();

    private List<Talk> talks ;
//
//    private EditText content;
//    private Button sendButton;
//    private ScrollView chatScroll ;
//    LinearLayout demandArea;
//    LinearLayout titleArea;
//    LinearLayout datetimeArea;
//    LinearLayout descArea;
//    LinearLayout howArea;
//    LinearLayout memberArea;
    LinearLayout commentsInfo ;
    LinearLayout statusArea;

//    LinearLayout talkArea;


//    List<MemberSummary> members = new ArrayList<MemberSummary>();

    private boolean changed = false;

    private ClipboardManager myClipboard;
    private ClipData myClip;

//    RadioGroup relaitonStatus;
//    TextView demandTxt;
//    TextView beginDateTxt;
//    TextView endDateTxt;
//    TextView memberTxt;
//    TextView titleTxt;
//    TextView descTxt;
//    TextView memoTxt;


    ProgressDialog progressDialog;
    Relation relation = new Relation();

    private Integer COMMENT_CODE = 500;
//    private Integer TITLE_CODE = 600;
//    private Integer DESC_CODE = 700;
//    private Integer ADD_MEMBER_CODE = 800;
//    private Integer ADD_DEMAND_CODE = 900;
//    private Integer ADD_PARTNER_CODE = 1000;
//    private Integer MEMO_CODE = 400;



    private boolean loading = false;

    private LinearLayout talkView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_relation_edit);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout


//        content = (EditText)findViewById(R.id.talk_content);


//        agreementArea = (android.support.v7.widget.CardView) findViewById(R.id.relation_agreements_area);
         commentArea =(android.support.v7.widget.CardView) findViewById(R.id.relation_comments_area);

         actionArea = (LinearLayout) findViewById(R.id.relation_action_area);
        partnersInfo = (LinearLayout) findViewById(R.id.relation_partners);


//        statusArea = (LinearLayout) findViewById(R.id.id_relation_status_area);
//         demandArea = (LinearLayout) findViewById(R.id.relation_demand_area);
//         titleArea = (LinearLayout) findViewById(R.id.relation_title_area);
//         datetimeArea= (LinearLayout) findViewById(R.id.relation_datetime_area);
//         descArea= (LinearLayout) findViewById(R.id.relation_desc_area);
//         howArea= (LinearLayout) findViewById(R.id.relation_how_area);
//         memberArea= (LinearLayout) findViewById(R.id.relation_member_area);
//        chatScroll = (ScrollView)findViewById(R.id.chat_scroll);

//        talkArea = (LinearLayout) findViewById(R.id.talk_area);

        consultAction = (LinearLayout) findViewById(R.id.id_summary_consult);

        consultAction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                consultIt();
            }
        });

//        relaitonStatus = (RadioGroup) findViewById(R.id.id_relation_status);
//
//        relaitonStatus.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup radioGroup, int i) {

//                if (!loading) {
//
//                    changed = true;
//                    if (i == R.id.id_relation_apply) {
//                        relation.setStatus("apply");
//                    }
//                    if (i == R.id.id_relation_ongoing) {
//                        relation.setStatus("ongoing");
//                    }
//                    if (i == R.id.id_relation_ever) {
//                        relation.setStatus("ever");
//                    }
//                    if (relation.getMatch_status().equals("agree") ){
//                        Common.setRelationAttrFeedback(RelationActivity.this,relation.getId(),relation.getMid(),"status",relation.getStatus());
//                    }
//                }
//            }
//        });


//        memoTxt =(TextView) findViewById(R.id.relation_memo);
//
//        memoTxt.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                Intent intent = new Intent();
//                intent.putExtra("type", "relation_memo");
//                intent.putExtra("content", relation.getMemo());
//                intent.setClass(RelationActivity.this, InputActivity.class);
//                startActivityForResult(intent, MEMO_CODE);
//            }
//        });
//
//        demandTxt = (TextView) findViewById(R.id.id_relation_demand);
//
//        demandTxt.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                confirmDemand();
//            }
//        });




        commentsInfo = (LinearLayout)findViewById(R.id.relation_comments);

//        titleTxt =(TextView) findViewById(R.id.id_relation_title);
//
//        titleTxt.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                completeTitle();
//            }
//        });



//        descTxt =(TextView) findViewById(R.id.id_relation_description);
//
//        descTxt.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                    Intent intent = new Intent();
//                    intent.putExtra("type", "relation_desc");
//                    intent.putExtra("content", relation.getDescription());
//                    intent.setClass(RelationActivity.this, InputActivity.class);
//                    startActivityForResult(intent, DESC_CODE);
//            }
//        });



        commentBtn = (Button) findViewById(R.id.relation_add_comment);

        commentBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.setClass(RelationActivity.this, CommentActivity.class);
                intent.putExtra("partner_id", relation.getId());
                intent.putExtra("is_new", true);
                startActivityForResult(intent, COMMENT_CODE);

            }
        });

        Button talkBtn = (Button) findViewById(R.id.relation_message);

        talkBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                 Intent intent = new Intent();
                intent.putExtra("from", "main");
                intent.putExtra("id", relation.getId());
                intent.putExtra("bid", 0);
                intent.putExtra("type", "match" );
                intent.setClass(RelationActivity.this, TalkActivity.class);
                startActivity(intent);

            }
        });


        

//        addPartnerBtn   = (Button) findViewById(R.id.relation_add_partner);
//
//        addPartnerBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                Intent intent = new Intent();
//                intent.setClass(RelationActivity.this, ConfirmUserActivity.class);
////                intent.putExtra("mid", relation.getMid());
////                intent.putExtra("id", relation.getId());
//                startActivityForResult(intent, ADD_PARTNER_CODE);
//
//            }
//        });



//        addBtn   = (Button) findViewById(R.id.relation_add);
//
//        addBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (checkComplete()) {
//                        addRelation();
//
//                }
//
//            }
//        });

//        confirmBtn   = (Button) findViewById(R.id.relation_confirm);
//
//        confirmBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (checkComplete()) {
//                        confirmIt();
//
//                }
//
//            }
//        });


        Button saveBtn = (Button) findViewById(R.id.relation_forever);

        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Common.setRelationAttrFeedback(RelationActivity.this, relation.getId(),relation.getMid() ,"status","save" );

            }
        });

        toggleBtn = (Button) findViewById(R.id.relation_delete);

        toggleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
                        setTitle("信息").
                        setMessage("确定操作吗？").
                        setIcon(R.drawable.ic_launcher).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                changed = true;
                                toggleIt( );
                            }
                        }).
                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).
                        create();
                alertDialog.show();


            }
        });

        talkView=(LinearLayout)findViewById(R.id.chat_list);
//
//        sendButton  = (Button) findViewById(R.id.send_talk);
//
//        sendButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                sendTalk();
//            }
//        });

        Intent intent = getIntent();
        is_new = intent.getBooleanExtra("is_new",false);

        if (is_new ) {

            relation.setStatus("ongoing");
            loading = true;
//            relaitonStatus.check(R.id.id_relation_ongoing);
            loading = false;
//            relaitonStatus.getChildAt(0).setEnabled(false);
//            relaitonStatus.getChildAt(0).setVisibility(View.INVISIBLE);

//            addBtn.setVisibility(View.VISIBLE);
//            addPartnerBtn.setVisibility(View.VISIBLE);
//            confirmBtn.setVisibility(View.GONE);
            commentBtn.setVisibility(View.GONE);
            toggleBtn.setVisibility(View.GONE);
            this.setTitle("添加合作");
        }else {
//            addBtn.setVisibility(View.GONE);
//            addPartnerBtn.setVisibility(View.GONE);
            Integer theid = intent.getIntExtra("id", 0);
            Integer themid = intent.getIntExtra("mid", 0);
            relation.setId(theid);
            relation.setMid( themid);

            loadData();
        }
//        loadDemands( );


    }
    public void renderVerify(){

        Intent intent = new Intent();
        intent.setClass(RelationActivity.this, VerifyActivity.class);
        startActivity(intent);
    }

    private void consultIt(  ) {


        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {
                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<BaseResponse> responseCall = svc.consult(userId,relation.getId(),0);
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {

                        if ( response != null) {

                            if (response.isSuccess()) {

                                Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
                                        setTitle("信息").
                                        setMessage(response.getMessage()).
                                        setIcon(R.drawable.ic_launcher).
                                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                loadData();
                                            }
                                        }).
                                        create();
                                alertDialog.show();


                            }else{
                                Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
                                        setTitle("信息").
                                        setMessage(response.getMessage()).
                                        setIcon(R.drawable.ic_launcher).
                                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                switch (response.getCondition()) {
                                                    case "verify":
                                                        renderVerify();
                                                        break;
                                                    case "charge":
                                                        renderMoney();
                                                        break;
                                                    default:
                                                }
                                            }
                                        }).
                                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                            }
                                        }).
                                        create();
                                alertDialog.show();
                            }
//                                Toast.makeText(getContext(),response.getMessage(),Toast.LENGTH_SHORT).show();

                        }else{
                            Toast.makeText(RelationActivity.this,"抱歉,处理失败，请重试。",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute((Void) null);

    }

//    private Integer demandChoice = 0;
//    private void confirmDemand( ){
//
//
//        if ( demands.size() == 0 ){
//            Intent intent = new Intent();
//
//            intent.setClass( RelationActivity.this, ConfirmHow.class);
//            intent.putExtra("is_new", true);
//            intent.putExtra("from", "relation"  );
//            startActivityForResult(intent ,ADD_DEMAND_CODE);
//            return;
//        }
//
//        ArrayList<String> list = new ArrayList<String>();
//
//        for (int i = 0; i < demands.size(); i++) {
//            DemandSummary ds = demands.get(i);
//            if (ds.getId().intValue() == relation.getDemand_id().intValue())
//                demandChoice = i;
//            list.add(ds.getTitle());
//        }
//
//        String[] items =  (String[])list.toArray(new String[0]);
//
//        AlertDialog.Builder singleChoiceDialog =
//                new AlertDialog.Builder(RelationActivity.this);
//        singleChoiceDialog.setTitle("选择业务");
//
//        // 第二个参数是默认选项，此处设置为0
//        singleChoiceDialog.setSingleChoiceItems(items, demandChoice,
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        demandChoice = which;
//                    }
//                });
//        singleChoiceDialog.setPositiveButton("确 定",
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        changed = true;
//
//                        relation.setDemand_id(demands.get(demandChoice).getId());
//                        demandTxt.setText( demands.get(demandChoice).getTitle());
//                        demandTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
//                        if (relation.getId()>0) {
//                            Common.setRelationAttrFeedback(RelationActivity.this,relation.getId(),relation.getMid(),"demand_id",relation.getDemand_id()+"");
//                        }
//
//                    }
//                });
//        singleChoiceDialog.setNegativeButton("取消",
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                    }
//                });
//        singleChoiceDialog.show();
//
//    }


//    private void loadDemands( ){
//
//        AsyncTask<Void, Void, GetMyDemandResponse> task =new AsyncTask<Void, Void, GetMyDemandResponse>() {
//            @Override
//            protected GetMyDemandResponse doInBackground(Void... params) {
//                AccountService svc = ServiceFactory.get(AccountService.class);
//                Call<GetMyDemandResponse> responseCall = svc.getMyDemand(userId, "false");
//                try {
//                    GetMyDemandResponse response = responseCall.execute().body();
//                    return response;
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                return null;
//            }
//            @Override
//            protected void onPostExecute(final GetMyDemandResponse response) {
//
//                demands = response.getContent();
//            }
//            @Override
//            protected void onCancelled() {
//
//            }
//        };
//        task.execute((Void)null);
//
//    }


//    private void completeEndDate() {
//
//        Calendar calendar = Calendar.getInstance();
//
//        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
//        Date dt = new Date();
//        try {
//            dt = formatter.parse( relation.getBegin_date().substring(0,10));
//        }  catch ( Exception e) {
//            e.printStackTrace();
//        }
//
//        calendar.setTime(dt);
//
//        int year=calendar.get(Calendar.YEAR);
//        int month=calendar.get(Calendar.MONTH);
//        int day=calendar.get(Calendar.DAY_OF_MONTH);
//
//        DatePickerDialog enddatePicker = new DatePickerDialog(RelationActivity.this, new DatePickerDialog.OnDateSetListener() {
//            @Override
//            public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
//                changed = true;
//                int day = datePicker.getDayOfMonth();
//                int month = datePicker.getMonth() ;
//                int year =  datePicker.getYear();
//
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//                calendar.set(year, month, day);
//                SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
//                relation.setEnd_date( formatter.format(calendar.getTime()));
//                endDateTxt.setText(relation.getEnd_date());
//                endDateTxt.setTextColor(getResources().getColor(R.color.colorTextPrimary));
//                if (relation.getId() == 0)return;
//                Common.setRelationAttr(relation.getId(),relation.getMid(),"end_date",relation.getEnd_date());
//
//            }
//        }, year, month, day);
//        enddatePicker.show();
//    }
//
//    private void completeBeginDate(){
//
//        Calendar calendar = Calendar.getInstance();
//        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
//        Date dt = new Date();
//        try {
//            dt = formatter.parse( relation.getBegin_date().substring(0,10));
//        }  catch ( Exception e) {
//            e.printStackTrace();
//        }
//
//        calendar.setTime(dt);
//
//        int year=calendar.get(Calendar.YEAR);
//        int month=calendar.get(Calendar.MONTH);
//        int day=calendar.get(Calendar.DAY_OF_MONTH);
//
//        DatePickerDialog begindatePicker = new DatePickerDialog(RelationActivity.this, new DatePickerDialog.OnDateSetListener() {
//            @Override
//            public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
//                changed = true;
//
//                int day = datePicker.getDayOfMonth();
//                int month = datePicker.getMonth() ;
//                int year =  datePicker.getYear();
//
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//                calendar.set(year, month, day);
//                SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
//                relation.setBegin_date(formatter.format(calendar.getTime()));
//                beginDateTxt.setText(relation.getBegin_date());
//                beginDateTxt.setTextColor(getResources().getColor(R.color.colorTextPrimary));
//                if (relation.getId() == 0)return;
//                Common.setRelationAttr(relation.getId(),relation.getMid(),"begin_date",relation.getBegin_date());
//
//            }
//        }, year, month, day);
//        begindatePicker.show();
//    }
//
//    private void completeTitle(){
//
//
//        Intent intent = new Intent();
//        intent.putExtra("type", "relation_title");
//        intent.putExtra("content", relation.getTitle());
//        intent.setClass(RelationActivity.this, InputActivity.class);
//        startActivityForResult(intent, TITLE_CODE);
//    }




//    public void refuseIt( ){
//
//
//        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
//            @Override
//            protected BaseResponse doInBackground(Void... params) {
//                AccountService svc = ServiceFactory.get(AccountService.class);
//                Call<BaseResponse> responseCall = svc.refuseRelation(userId,relation.getId());
//                BaseResponse ret = null ;
//                try {
//                    ret = responseCall.execute().body();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    ret = null;
//                }
//                return ret;
//            }
//
//            @Override
//            protected void onPostExecute(final BaseResponse response) {
//                if (response != null) {
//
//                    if (response.isSuccess()) {
//                        Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                                setTitle("信息").
//                                setMessage(response.getMessage()).
//                                setIcon(R.drawable.ic_launcher).
//                                setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        changed = true;
//                                        Intent intent = new Intent();
//                                        intent.putExtra("changed", changed );
//                                        setResult(666, intent);
//                                        finish();
//                                    }
//                                }).
//                                create();
//                        alertDialog.show();
//
//
//                    }else{
//                        Common.alert(RelationActivity.this,response.getMessage());
//                    }
//
//                } else {
//                    Common.alert(RelationActivity.this,"处理失败。");
//                }
//            }
//
//            @Override
//            protected void onCancelled() {
//            }
//        };
//        task.execute((Void) null);
//
//    }
//    public void confirmIt( ){
//
//        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
//            @Override
//            protected BaseResponse doInBackground(Void... params) {
//                AccountService svc = ServiceFactory.get(AccountService.class);
//                Call<BaseResponse> responseCall = svc.confirmRelation(userId,relation.getId(),relation.getStatus(),relation.getDemand_id(),relation.getMemo());
//                BaseResponse ret = null ;
//                try {
//                    ret = responseCall.execute().body();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    ret = null;
//                }
//                return ret;
//            }
//
//            @Override
//            protected void onPostExecute(final BaseResponse response) {
//                if (response != null) {
//
//                    if (response.isSuccess()) {
//                        Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                                setTitle("信息").
//                                setMessage(response.getMessage()).
//                                setIcon(R.drawable.ic_launcher).
//                                setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        changed = true;
//                                        Intent intent = new Intent();
//                                        intent.putExtra("changed", changed );
//                                        setResult(666, intent);
//                                        finish();
//                                    }
//                                }).
//                                create();
//                        alertDialog.show();
//
//
//                    }else{
//
//                            Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                                    setTitle("信息").
//                                    setMessage(response.getMessage()).
//                                    setIcon(R.drawable.ic_launcher).
//                                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                                        @Override
//                                        public void onClick(DialogInterface dialog, int which) {
//                                            if (response.getCondition().equals("charge")) {
//                                                renderMoney();
//                                            }
//                                        }
//                                    }).
//                                    create();
//                            alertDialog.show();
//
//                    }
//
//                } else {
//                    Common.alert(RelationActivity.this,"处理失败。");
//                }
//            }
//
//            @Override
//            protected void onCancelled() {
//            }
//        };
//        task.execute((Void) null);
//
//    }
//


    private void renderMoney( ){

        Intent intent = new Intent();
        intent.putExtra("money", 100.0);
        intent.setClass(RelationActivity.this, MoneyActivity.class);
        startActivity(intent);
    }

//
//    private void deletePartner(final Integer userid){
//        final String useridstr = userid +"";
//        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
//            @Override
//            protected BaseResponse doInBackground(Void... params) {
//                AccountService svc = ServiceFactory.get(AccountService.class);
//                Call<BaseResponse> responseCall = svc.setRelationAttr(userId,relation.getId(),relation.getMid(),"delpartners",useridstr);
//                BaseResponse response = null ;
//                try {
//                    response = responseCall.execute().body();
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                return response;
//            }
//
//            @Override
//            protected void onPostExecute(final BaseResponse response) {
//                if (response != null) {
//                    if ( ! response.getMessage().equals("") ) {
//                        Common.alert(RelationActivity.this,response.getMessage());
//                    }
//                    ArrayList<PartnerSummary> it = new ArrayList<PartnerSummary>();
//                    for (PartnerSummary ps : relation.getPartners()){
//                        if (ps.getUser_id() != userid){
//                            it.add(ps);
//                        }
//                    }
//                    relation.setPartners( it);
//
//                    renderPartners();
//                } else {
//                    Common.alert(RelationActivity.this,"系统发生错误");
//
//                }
//            }
//
//            @Override
//            protected void onCancelled() {
//            }
//        };
//        task.execute((Void) null);
//    }

    public void toggleIt(  ){
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = null;
                if (relation.getStatus().equals("quit")) {
                    responseCall = svc.cancelquit(userId, relation.getId(), relation.getMid());
                }else{
                    responseCall = svc.quit(userId, relation.getId(), relation.getMid());
                }
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {

                    if (response.isSuccess()) {
                        Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
                                setTitle("信息").
                                setMessage(response.getMessage()).
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        loadData();
                                    }
                                }).
                                create();
                        alertDialog.show();

                    }else{
                        Common.alert(RelationActivity.this,response.getMessage());
                    }

                } else {
                    Common.alert(RelationActivity.this,"处理失败。");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    private void renderPartners(){
        partnersInfo.removeAllViews();
        if (CollectionUtil.notEmpty(relation.getPartners())) {
            //合作的人

            for (final com.woyao.core.model.PartnerSummary partner : relation.getPartners()) {

                LinearLayout item = (LinearLayout) LayoutInflater.from(RelationActivity.this).inflate(R.layout.partner_summary_item, null);
                final ImageView demandImage = (ImageView) item.findViewById(R.id.partner_demand_image);
                final  CircleImageView snailview = (CircleImageView) item.findViewById(R.id.partner_avatar);
                final TextView title = (TextView) item.findViewById(R.id.partner_title);
                final TextView desc = (TextView) item.findViewById(R.id.partner_desc);
                final TextView displayname = (TextView) item.findViewById(R.id.partner_displayname);
                final Button call = (Button) item.findViewById(R.id.partner_call);
                final Button wechat = (Button) item.findViewById(R.id.partner_wechat);
                final Button email = (Button) item.findViewById(R.id.partner_email);
                final Button office = (Button) item.findViewById(R.id.partner_office);
//                final Button toggleBtn = (Button) item.findViewById(R.id.partner_delete);
                final LinearLayout info = (LinearLayout) item.findViewById(R.id.partner_info);

                if (partner.getMobile().equals("")) {
                    call.setVisibility(View.GONE);
                }

//                if (partner.getDeletable()){
//                    toggleBtn.setVisibility(View.VISIBLE);
//                }else{
//                    toggleBtn.setVisibility(View.GONE);
//                }

                title.setText(partner.getTitle());
                desc.setText(partner.getDescription());
                displayname.setText( partner.getDisplayname());

                if (StringUtil.notNullOrEmpty(partner.getSnailview())) {
                    Picasso.with(this)
                            .load(partner.getSnailview())
                            .into(snailview);
                }




                call.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        Uri data = Uri.parse("tel:" + partner.getMobile());
                        intent.setData(data);
                        startActivity(intent);
                    }
                });

                if (partner.getWechat().equals("")){
                    wechat.setVisibility(View.GONE);
                }

                wechat.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
                                setTitle("微信号").
                                setMessage(partner.getWechat()).
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("复制", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                                        myClip = ClipData.newPlainText("text", partner.getWechat());
                                        myClipboard.setPrimaryClip(myClip);
                                    }
                                }).
                                create();
                        alertDialog.show();
                    }
                });

                if (partner.getEmail().equals("")){
                    email.setVisibility(View.GONE);
                }

                email.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
                                setTitle("电子邮件").
                                setMessage(partner.getEmail()).
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("复制", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                                        myClip = ClipData.newPlainText("text", partner.getEmail());
                                        myClipboard.setPrimaryClip(myClip);
                                    }
                                }).
                                create();
                        alertDialog.show();
                    }
                });

                if (partner.getOffice().equals("")){
                    office.setVisibility(View.GONE);
                }
                office.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
                                setTitle("办公地址").
                                setMessage(partner.getOffice()).
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("复制", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                                        myClip = ClipData.newPlainText("text", partner.getOffice());
                                        myClipboard.setPrimaryClip(myClip);
                                    }
                                }).
                                create();
                        alertDialog.show();
                    }
                });

//                toggleBtn.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                                setTitle("信息").
//                                setMessage("删除合作成员吗？").
//                                setIcon(R.drawable.ic_launcher).
//                                setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        deletePartner( partner.getUser_id());
//                                    }
//                                }).
//                                setNegativeButton("取消", new DialogInterface.OnClickListener() {
//
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//
//                                    }
//                                }).
//                                create();
//                        alertDialog.show();
//                    }
//                });


                snailview.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.putExtra("id",partner.getUser_id() );
                        intent.setClass(RelationActivity.this, PersonViewActivity.class);
                        startActivity(intent);

                    }
                });
                info.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        if (partner.getDemand_id() >0 ){
                            Intent intent = new Intent();
                            intent.putExtra( "id", partner.getDemand_id());
                            intent.setClass( RelationActivity.this, ChanceViewActivity.class);
                            startActivity(intent );
                        }else{
                            Common.alert(RelationActivity.this,"合作方业务未确认");
                        }

                    }
                });

                partnersInfo.addView(item);
                View splitter = (View) LayoutInflater.from(RelationActivity.this).inflate(R.layout.splitter, null);
                partnersInfo.addView(splitter);
            }
        }

    }
    private void renderIt() {
        loading = true;

        this.setTitle(relation.getCaption());

        renderPartners();
        if ( relation.getStatus().equals("quit")){
            toggleBtn.setText("继续合作");
        }else{
            toggleBtn.setText("结束合作");
        }
//        if (relation.getStatus().equals("match")){
//            if (relation.getRelation_status().equals("ever")) {
//                relaitonStatus.check(R.id.id_relation_ever);
//            } else if (relation.getRelation_status().equals("ongoing")) {
//                relaitonStatus.check(R.id.id_relation_ongoing);
//            } else {
//                relaitonStatus.check(R.id.id_relation_apply);
//            }
//        }else if (relation.getStatus().equals("ever")) {
//            relaitonStatus.check(R.id.id_relation_ever);
//        } else if (relation.getStatus().equals("ongoing")) {
//            relaitonStatus.check(R.id.id_relation_ongoing);
//        } else if (relation.getStatus().equals("refer")) {
//            statusArea.setVisibility(View.GONE);
////            demandArea.setVisibility(View.GONE);
//            consultAction.setVisibility(View.GONE);
//        }

//        if (relation.getDemand_id() > 0) {
//            demandTxt.setText(relation.getDemand_title());
//            demandTxt.setTextColor(getResources().getColor(R.color.colorTextDarkGrey));
//        }
//
//        if (!relation.getMemo().equals("")) {
//            memoTxt.setText(relation.getMemo());
//        }

        commentsInfo.removeAllViews();
        if (CollectionUtil.notEmpty(relation.getComments())) {


            //合作的人
            LinearLayout item1 = (LinearLayout) LayoutInflater.from(RelationActivity.this).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);
            title1.setText("评论：" + relation.getComments().size());
            commentsInfo.addView(item1);
            for (final com.woyao.core.model.CommentSummary comment : relation.getComments()) {

                LinearLayout item = (LinearLayout) LayoutInflater.from(RelationActivity.this).inflate(R.layout.comment_item, null);

                final TextView title = (TextView) item.findViewById(R.id.comment_title);
                final TextView rate = (TextView) item.findViewById(R.id.comment_rate);
                final TextView desc = (TextView) item.findViewById(R.id.id_comment_description);

                title.setText(comment.getTitle());
                desc.setText(comment.getDescription());
                String rateStr = "";
                for (int i = 0; i < comment.getRate(); i++) {
                    rateStr = rateStr + "★";
                }
                rate.setText(rateStr);

                item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.putExtra("id", comment.getId());
                        intent.putExtra("is_new", false);
                        intent.setClass(RelationActivity.this, CommentActivity.class);
                        startActivityForResult(intent, COMMENT_CODE);
                    }
                });

                commentsInfo.addView(item);
                View splitter = (View) LayoutInflater.from(RelationActivity.this).inflate(R.layout.splitter, null);
                commentsInfo.addView(splitter);
            }
        }



        if (relation.getCommentable()){
            commentBtn.setEnabled(true);
        }else{
            commentBtn.setEnabled(false);
        }

//        if (relation.getStatus().equals("match") && !relation.getMatch_status().equals("end")){
//            confirmBtn.setVisibility(View.VISIBLE);
//        }else{
//            confirmBtn.setVisibility(View.GONE);
//        }

//        if (relation.getTalkable()){
//            talkArea.setVisibility(View.VISIBLE);
//        }else{
//            talkArea.setVisibility(View.GONE);
//        }

//        if (!relation.getAddable()){
//            addPartnerBtn.setVisibility(View.GONE);
//        }else{
//            addPartnerBtn.setVisibility(View.VISIBLE);
//        }

        loading = false;

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", changed );
        setResult(666, intent);
        finish();
        return true;
    }

//    private boolean checkComplete(){
//
//        if ( relation.getPartners().size() == 0){
//            Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                    setTitle("信息").
//                    setMessage("请选择合作伙伴").
//                    setIcon(R.drawable.ic_launcher).
//                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//
//                        }
//                    }).
//                    create();
//            alertDialog.show();
//
//            return false;
//        }

//        if (relation.getHezuo_status().equals( "ongoing" ) || relation.getHezuo_status().equals("ever")) {
//            if (relation.getTitle().equals("")) {
//                Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                        setTitle("信息").
//                        setMessage("请填写合作事宜").
//                        setIcon(R.drawable.ic_launcher).
//                        setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                completeTitle();
//                            }
//                        }).
//                        create();
//                alertDialog.show();
//
//                return false;
//            }
//
//            if (relation.getHow().equals("")) {
//                Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                        setTitle("信息").
//                        setMessage("请选择合作领域").
//                        setIcon(R.drawable.ic_launcher).
//                        setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                completeHow();
//                            }
//                        }).
//                        create();
//                alertDialog.show();
//                return false;
//            }
//
//
//
//            if (relation.getBegin_date().equals("")) {
//                Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                        setTitle("信息").
//                        setMessage("请选择合作开始时间").
//                        setIcon(R.drawable.ic_launcher).
//                        setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                completeBeginDate();
//                            }
//                        }).
//                        create();
//                alertDialog.show();
//                return false;
//            }
//
//            if ( relation.getStatus().equals("ever") && relation.getEnd_date().equals("")){
//                Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                        setTitle("信息").
//                        setMessage("请选择合作结束时间").
//                        setIcon(R.drawable.ic_launcher).
//                        setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                completeEndDate();
//                            }
//                        }).
//                        create();
//                alertDialog.show();
//                return false;
//            }
//
//            if (relation.getMember_id() == 0) {
//                Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                        setTitle("信息").
//                        setMessage("请选择合作身份").
//                        setIcon(R.drawable.ic_launcher).
//                        setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                confirmMember();
//                            }
//                        }).
//                        create();
//                alertDialog.show();
//                return false;
//            }
//
//        }else{
//            if (relation.getDemand_id() == 0) {
//                Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                        setTitle("信息").
//                        setMessage("请选择业务").
//                        setIcon(R.drawable.ic_launcher).
//                        setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                confirmDemand();
//                            }
//                        }).
//                        create();
//                alertDialog.show();
//                return false;
//            }
////        }
//        return true;
//    }

//    private void addRelation(){
//        progressDialog = new ProgressDialog(this);
//        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//        progressDialog.setMessage("正在处理······");
//        progressDialog.show();
//
//        AsyncTask<Void, Void, BaseResponse> needTask = new AsyncTask<Void, Void, BaseResponse>() {
//            @Override
//            protected BaseResponse doInBackground(Void... params) {
//                AccountService svc = ServiceFactory.get(AccountService.class);
//                Call<BaseResponse> responseCall = svc.addRelation(userId,relation.getPartners().get(0).getDemand_id(),relation.getStatus(),relation.getDemand_id(),relation.getMemo());
//                try {
//                    BaseResponse response = responseCall.execute().body();
//                    return response;
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                return null;
//            }
//
//            @Override
//            protected void onPostExecute(final BaseResponse response) {
//                if (response != null ) {
//                    if  (response.isSuccess()){
//
//                        Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                                setTitle("信息").
//                                setMessage("已经添加，待合作方确认").
//                                setIcon(R.drawable.ic_launcher).
//                                setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        changed = true;
//                                        Intent intent = new Intent();
//                                        intent.putExtra("changed", changed );
//                                        setResult(666, intent);
//                                        finish();
//                                    }
//                                }).
//                                create();
//                        alertDialog.show();
//
//                    }else{
//                        Common.alert(RelationActivity.this,response.getMessage());
//                    }
//                }
//                progressDialog.dismiss();
//            }
//        };
//        needTask.execute((Void) null);
//    }
//



    private void loadData() {



        AsyncTask<Void, Void, GetRelationResponse> needTask = new AsyncTask<Void, Void, GetRelationResponse>() {
            @Override
            protected GetRelationResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetRelationResponse> responseCall = svc.getRelation(userId, relation.getId(),relation.getMid());
                try {
                    GetRelationResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(final GetRelationResponse response) {
                if (response != null && response.getContent() != null) {
                    relation = response.getContent();

                    if (response.isSuccess()) {
                        renderIt();
                    }else{
                        Common.alert(RelationActivity.this, response.getMessage());
                    }
                }
//                progressDialog.dismiss();
            }
        };
        needTask.execute((Void) null);
    }

//    private void loadMembers(){
//
//        AsyncTask<Void, Void, GetMyMemberResponse> task =new AsyncTask<Void, Void, GetMyMemberResponse>() {
//            @Override
//            protected GetMyMemberResponse doInBackground(Void... params) {
//                AccountService svc = ServiceFactory.get(AccountService.class);
//                Call<GetMyMemberResponse> responseCall = svc.getMyMember(userId,"","");
//                try {
//                    GetMyMemberResponse response = responseCall.execute().body();
//                    return response;
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                return null;
//            }
//            @Override
//            protected void onPostExecute(final GetMyMemberResponse response) {
//                if (response != null && response.getContent() !=null){
//                    members = response.getContent();
//                    if (relation.getId() == 0 ){
//                        for ( MemberSummary ms : members){
//                            if (ms.getCurrent()){
//                                relation.setMember_id( ms.getId() );
//                                relation.setMember_title(ms.getTitle());
//                                memberTxt.setText( relation.getMember_title());
//                                memberTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
//                                changed = true;
//                                break;
//                            }
//                        }
//
//
//                    }
//                }
//
//            }
//            @Override
//            protected void onCancelled() {
//            }
//        };
//        task.execute((Void)null);
//    }
//
//



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == COMMENT_CODE  && resultCode == 666 ) {
            changed = true;
            loadData();
        }

//        if(requestCode == TITLE_CODE  && resultCode == 666 ) {
//            changed = true;
//            CharSequence con = data.getCharSequenceExtra("content");
//            if (con == null) return;
//            titleTxt.setTextColor(getResources().getColor(R.color.colorTextDarkGrey) );
//            titleTxt.setText( con);
//            relation.setTitle(con.toString());
//            if (relation.getId() > 0) {
//                Common.setRelationAttr(relation.getId(), relation.getMid(), "title", relation.getTitle());
//            }
//
//        }
//        if(requestCode == DESC_CODE  && resultCode == 666 ) {
//            changed = true;
//            CharSequence con = data.getCharSequenceExtra("content");
//            if (con == null) return;
//            descTxt.setTextColor(getResources().getColor(R.color.colorTextDarkGrey) );
//            descTxt.setText( con);
//            relation.setDescription(con.toString());
//            if (relation.getId() > 0) {
//                Common.setRelationAttr(relation.getId(), relation.getMid(), "description", relation.getDescription());
//            }
//        }
//
//        if(requestCode == MEMO_CODE  && resultCode == 666 ) {
//            changed = true;
//            CharSequence con = data.getCharSequenceExtra("content");
//            if (con == null) return;
//            memoTxt.setText( con);
//            relation.setMemo(con.toString());
//            if (relation.getId() > 0) {
//                Common.setRelationAttr(relation.getId(), relation.getMid(), "memo", relation.getMemo());
//            }
//        }
//        if(requestCode == ADD_MEMBER_CODE ) {
//            loadMembers();
//        }
//
//        if(requestCode == ADD_PARTNER_CODE && resultCode == 666  ) {
//            PartnerList partners = (PartnerList)data.getExtras().get("partners");
//            relation.getPartners().clear();
//            relation.getPartners().addAll( partners.getContent() );
//            renderPartners();
//
//            if (!is_new){
//                ArrayList<String> it = new ArrayList<String>();
//
//                for (PartnerSummary ps : partners.getContent()){
//                        it.add(ps.getUser_id().toString());
//
//                }
//                Common.setRelationAttrFeedback(RelationActivity.this,relation.getId(),relation.getMid(),"partners", Common.listToString(it ));
//            }
//        }
//
//        if(requestCode == ADD_DEMAND_CODE ) {
//            loadDemands();
//        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("changed", changed );
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}